<template>
  <div class="location-box">
    <el-row :gutter="20">
      <!-- 货位数据 -->
      <el-col :sm="10" :md="10" :lg="10">
        <!-- 搜索 -->
        <el-input v-model="searchName" placeholder="请输入货位名称" clearable size="small" prefix-icon="el-icon-search"
          style="margin-bottom:10px" />
        <div class="height-tree">
          <el-tree default-expand-all :data="locationTree" node-key="sortId" :props="defaultProps"
            :filter-node-method="filterNode" ref="tree" v-loading="loading" :highlight-current="isHeight"
            @node-click="nodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }" style="width: 100%"
              @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)">
              <div class="chang-mourse">
                  <span><span>{{ node.label}}</span><span v-if="data.parentId==0">-{{whName}}</span></span>
                <span class="mou-r" v-if="isOperation">
                  <el-link v-hasPermi="['wm:location:add']"  v-show="data.opShow" size="mini" type="primary" icon="el-icon-plus"
                    @click.stop="addLocation(node)">
                  </el-link>
                  <el-link v-hasPermi="['wm:location:edit']"  v-show="data.opShow&&data.parentId!==0" size="mini" style="color: #67c23a;" type="primary"
                    icon="el-icon-edit" @click.stop="uplateSort(node)"></el-link>
                  <el-link v-hasPermi="['wm:location:remove']" v-show="data.opShow&&data.parentId!==0" size="mini" style="color: #f56c6c;" type="primary"
                    icon="el-icon-delete" @click.stop="remove(node)"></el-link>
                </span>
              </div>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :sm="14" :md="14" :lg="14">
        <div class="location-content">
          <el-form :model="locationForm" :rules="rules" ref="locationForm" label-width="78px"
            :disabled="btnChange == 'seeStatus'">
            <el-form-item label="上级货位" class="superior-class" v-if="isParentId">
              <el-input v-model="parentName" disabled></el-input>
            </el-form-item>
            <el-form-item label="货位名称" prop="location">
              <el-input v-model="locationForm.location"></el-input>
            </el-form-item>
            <el-form-item label="最大重量" prop="maxWeight">
              <el-input v-model="locationForm.maxWeight"></el-input>
            </el-form-item>
            <el-form-item label="最大容积" prop="maxSize">
              <el-input v-model="locationForm.maxSize"></el-input>
            </el-form-item>
            <div style="margin-top: 10px;">
              <el-form-item label="货位状态" class="ma-lable">
                <el-select v-model="locationForm.status">
                  <el-option label="正常" value="0"></el-option>
                  <el-option label="停用" value="1"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="handle-save">
            <el-button v-hasPermi="['wm:location:add']" type="primary" v-if="btnChange == 'addStatus' " icon="el-icon-edit"
              @click="submitFrom('locationForm',treeNode)">确定
            </el-button>
            <el-button v-hasPermi="['wm:location:edit']" type="success" v-if="btnChange == 'seeStatus'&&isParentId " icon="el-icon-edit"
              @click="handleUpdate">修改
            </el-button>
            <el-button v-hasPermi="['wm:location:edit']" type="success" v-if="btnChange == 'updateStatus' " icon="el-icon-edit"
              @click="submitFrom('locationForm',treeNode)">保存
            </el-button>
            <el-button v-hasPermi="['wm:location:add']" icon="el-icon-refresh" @click="reset"
              v-if="btnChange == 'addStatus' || btnChange == 'updateStatus'">重置</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {
    isSerial,
    supParent,
    selectNode,
    getCurrentNode,
    setCurrentNode,
    getTreeData
  } from "../../utils/sort.js" //js方法
  import {
    listLocation,
    addLocation,
    updateLocation,
    delLocation,
  } from "../../api/warehouses"; //接口
  export default {
    data() {
      return {
        loading: true,
        isHeight: false,
        // 上级货位名称
        parentName: "",
        //父货位id
        parentId: 0,
        //上级货位是否显示
        isParentId: false,
        //element-ui表头样式
        activeName: 'basicinfo',
        //树形节点
        treeNode: "",
        // 货位数据
        locationTree: [],
        //绑定树形数据名称
        defaultProps: {
          children: 'children',
          label: 'location',
        },
        btnChange: "addStatus",
        //货位表单
        locationForm: {
          parentId: "",
          location: "",
          maxWeight: "",
          maxSize: "",
          status: "0",
        },
        // 搜索名称
        searchName: "",
        rules: {
          location: [{
            required: true,
            trigger: 'blur'
          }],
        }
      }
    },
    props: {
      // 是否显示操作按钮
      isOperation: {
        type: Boolean,
        default: true
      },
      whCode: {
        type: String,
        default: ""
      },
      whName: {
        type: String,
        default: ""
      }
    },
    created() {
      this.getTreeList();
      console.log(this.whName)
    },
    methods: {
      //获取货位数据
      getTreeList() {
        this.loading = true;
        listLocation({
          whCode: this.whCode
        }).then(res => {
          let whArr = [];
          whArr.push(res.data);
          this.locationTree = getTreeData(whArr); //当children为0时，赋值undefined
          this.parentId = this.locationTree[0].locId;
          this.parentName = this.locationTree[0].location;
          this.loading = false;
        });
      },

      //货位树选中
      nodeClick(data, node) {
        this.isHeight = false;
        this.btnChange = 'seeStatus';
        this.locationForm.parentId = data.parentId
        this.locationForm.location = data.location;
        this.locationForm.maxWeight = data.maxWeight;
        this.locationForm.maxSize = data.maxSize;
        this.locationForm.status = data.status;
        this.parentId = this.locationForm.parentId; //保存parentId，用来不触发新增按钮form提交
        this.treeNode = node; //节点赋值，用来确定添加位置
        if (data.parentId == 0) {
          this.isParentId = false; //父类名称为隐藏
        } else {
          this.isParentId = true;
        }
        this.uplateAdd(node) //修改新增公共方法
      },

      // 从查看切换修改按钮
      handleUpdate() {
        this.btnChange = 'updateStatus';
      },

      //添加子货位
      addLocation(node) {
        this.reset() //重置表单内容
        this.btnChange = 'addStatus'; //按钮状态为添加
        this.uplateAdd(node); //修改新增公共方法
        this.parentId = node.data.locId; //保存parentId，用来不刷新时表单提交
        this.treeNode = node; //节点赋值，用来确定添加位置
        this.isParentId = true;
      },

      // 修改货位新增货位公共方法
      uplateAdd(node) {
        // 上级货位高亮
        this.isHeight = true;
        const getNode = [];
        getCurrentNode(node, getNode).then(currentNode => {
          setCurrentNode(this.$refs.tree.root, currentNode)
        })
        // 获取上级货位名称
        const name = [];
        const getParentName = supParent(node, name).reverse(); //获取上级货位名称
        const parentName = getParentName.join(" / "); //拼接上级货位名称
        if (node.data.parentId == 0) {
          this.parentName = node.data.location; //主类上级货位为自身
        } else if (this.btnChange == 'addStatus') {
          this.parentName = parentName + " / " + node.data.location //子类上级货位最终结果
        } else {
          this.parentName = parentName;
        }
      },

      //修改货位
      uplateSort(node) {
        this.btnChange = 'updateStatus'; //按钮状态为保存
        this.uplateAdd(node) //修改新增公共方法
        this.locationForm = Object.assign({}, node.data); //拷贝表单内容，避免影响数据
        this.parentId = this.locationForm.parentId; //保存parentId，用来不触发新增按钮form提交
        this.treeNode = node; //节点赋值，用来确定添加位置
        if (node.data.parentId == 0) { //父类Id为0，代表添加主货位
          this.isParentId = false; //父类名称为隐藏
        } else {
          this.isParentId = true;
        }
      },

      //移除货位
      remove(node) {
        this.$confirm('确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLocation(node.data.locId);
        }).then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.reset(); //重置表单
            this.isHeight = false;
            this.isParentId = false; //父类名称为隐藏
            this.parentId = 0; //父类Id为0，代表添加主货位
            this.butChange = 'addStatus'; //按钮状态为添加
            this.$refs.tree.remove(node) //移除节点
          }
        })
      },

      //鼠标进入事件
      mouseenter(data) {
        this.$set(data, "opShow", true);
      },

      //鼠标离开事件
      mouseleave(data) {
        this.$set(data, "opShow", false);
      },

      // 树形筛选
      filterNode(value, data) {
        if (!value) return true;
        return data.sortName.indexOf(value) !== -1;
      },

      //提交表单
      submitFrom(locationForm, node) {
        this.$refs[locationForm].validate((valid) => {
          if (valid) {
            this.locationForm.parentId = this.parentId; //赋值parentId，用来不刷新时表单提交
            if (this.btnChange == "addStatus") { //触发新增提交
              addLocation(this.locationForm).then(res => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  if (node == "") {
                    this.locationTree[0].children.push(res.data)
                  } else {
                    node.expand();
                    this.$refs.tree.append(res.data, node) //不刷新更新节点数据
                  }
                  this.reset(); //重置表单
                }

              }).catch(err => {
                this.msgError("新增失败");
              })

            } else {
              this.locationForm.parentId = this.parentId; //赋值parentId，用来不刷新时表单提交
              updateLocation(this.locationForm).then(res => { //触发保存提交
                if (res.code == 200) {
                  this.msgSuccess("保存成功");
                  this.locationForm.version = res.data.version; //保存version，用来不刷新修改
                  node.data.location = this.locationForm.location;
                  node.data.maxWeight = this.locationForm.maxWeight;
                  node.data.maxSize = this.locationForm.maxSize;
                  node.data.status = this.locationForm.status;
                  node.data.version = res.data.version;
                }

              }).catch(err => {
                this.msgError("保存失败");
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      // 表单重置
      reset() {
        this.locationForm.location = "";
        this.locationForm.status = "0";
        this.locationForm.maxWeight = "";
        this.locationForm.maxSize = "";
      },
    },
    watch: {
      searchName: {
        handler(newData) {
          this.$refs.tree.filter(newData);
        },
        deep: true
      }
    }

  }
</script>

<style lang="scss">
  .location-box {
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
      background: none !important;
      color: #1890FF !important;
    }

    .superior-class .el-input.is-disabled .el-input__inner {
      color: #1890FF !important;
    }

    .custom-tree-node {
      font-size: 14px;

      a {
        margin-left: 10px;

        &:hover i {
          font-weight: 700;

        }
      }

      .el-link.is-underline:hover:after {
        border: none !important;

      }
    }

    .chang-mourse {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .mou-r {
        margin-right: 10px;
      }
    }

    .height-tree {
      height: calc(100vh - 390px);
      overflow: auto;

    }

    .location-content {
      border: 1px solid #ebebeb;
      padding: 30px 20px 30px 30px;
      border-radius: 5px;
    }

    .handle-save {
      margin-top: 20px;
      text-align: right;
      margin-right: 10px;

      .el-button--medium {
        padding: 8px;
        font-size: 13px;
      }

      .el-button--info {
        background: #ccc;
      }
    }
  }
</style>
